//
//  AppDelegate.m
//  MobileOffice
//
//  Created by 晓 on 2019/5/30.
//  Copyright © 2019 com.idolmedia. All rights reserved.
//

#import "AppDelegate.h"
#import "MOTabBarViewController.h"
#import "MOLoginViewController.h"
#import "MOOpenAppViewController.h"

//vpn
#import "SDKWrapper.h"
#import <SecurePortal/LibSecIDLite.h>

//友盟
#import <UMCommon/UMCommon.h>
#import <UMAnalytics/MobClick.h>

NSString* const kVPN_HOST              = @"222.82.235.40";
NSString* const kVPN_PORT              = @"7001";
NSString* const kLOGIN_USERNAME        = @"zhangsan";
NSString* const kLOGIN_PASSSWORD       = @"qianxin@2019#";
NSString* const kVPN_AUTH_NAME         = @"本地认证";


@interface AppDelegate ()<UITabBarControllerDelegate>

@property(nonatomic,strong)NSTimer *timer;

@property(nonatomic,strong)NSTimer *timer1;


@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 1.创建窗口
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = KWhiteColor;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 12.1) {
        //解决12.1系统 tabbar错位
        [UITabBar appearance].translucent = NO;
    }
    
    //设置键盘
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [IQKeyboardManager sharedManager].shouldShowToolbarPlaceholder = NO;
    
    // 设置窗口的根控制器
    NSString *usName = [[NSUserDefaults standardUserDefaults] objectForKey:@"USER_NEW_USERNAME"];
    NSString *usToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"USER_NEW_TOKEN"];
    
    if (usName.length>0&&usToken.length>0) {
        
        NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"enterBackTime"];
        if ([str integerValue]==1) {
            MOOpenAppViewController *vc = [[MOOpenAppViewController alloc]init];
            [self.window setRootViewController:vc];
        }else{
            [self creatTabbar];
        }
    }else{
        MOLoginViewController *vc = [[MOLoginViewController alloc]init];
        [self.window setRootViewController:vc];
    }

    //vpn
    [self vpnLogIn];
    
    //友盟
    //开发者需要显式的调用此函数，日志系统才能工作
    [UMConfigure setLogEnabled:YES];
    [UMConfigure initWithAppkey:@"5dce5b834ca357824b000bc4" channel:@"App Store"];
    
    [MobClick setScenarioType:0];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(userDidTakeScreenshotNotification:)
                                                 name:UIApplicationUserDidTakeScreenshotNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(vpnLogIn) name:@"vpnLoginNew" object:nil];
    [self.window makeKeyAndVisible];
    
    return YES;
}



-(void)creatTabbar
{
    [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"enterBackTime"];
    
    MOTabBarViewController *tabVC = [[MOTabBarViewController alloc] init];
    tabVC.delegate = self;
    [self.window setRootViewController:tabVC];
}

-(void)outLogin
{
    MOLoginViewController *vc = [[MOLoginViewController alloc]init];
    [self.window setRootViewController:vc];
}

-(void)vpnLogIn
{
    NSDictionary *loginDic = @{@"vpn_host"      : kVPN_HOST,
                               @"vpn_port"      : kVPN_PORT,
                               @"auth_server"   : kVPN_AUTH_NAME,
                               @"auth_username" : kLOGIN_USERNAME,
                               @"auth_password" : kLOGIN_PASSSWORD,
                               @"auth_mode"     : @0,
                               @"auth_autologin": @1,
                               @"extra_test_param1" : @"extra_test_param1",
                               };
    
    SDKWrapper* sdkWrapper = [SDKWrapper getInstance];
    [sdkWrapper runWithParams:loginDic responseHandler:^(BOOL result) {
        if(result)
        {
            NSLog(@"Login Succees");
            [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"vpnLogin"];
            [self senCodeAgain];
            [[ADShowMessage shareShowMessage]showTextOnly:@"vpn连接成功" showInView:WINDOW];
        }
        else
        {
            NSLog(@"Login Fail");
            [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"vpnLogin"];
            [[ADShowMessage shareShowMessage]showTextOnly:@"vpn连接失败" showInView:WINDOW];
        }
    }];
}

-(void)senCodeAgain{
    NSString *str = [[NSUserDefaults standardUserDefaults]objectForKey:@"sendCodeField"];
    if ([str integerValue]==1) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"sendCodeAgain" object:nil];
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.

}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:90 target:self selector:@selector(changeData) userInfo:nil repeats:NO];
    
    _timer1 = [NSTimer scheduledTimerWithTimeInterval:45 target:self selector:@selector(outVpn) userInfo:nil repeats:NO];
    
    //实现一个可以后台运行几分钟的权限, 当用户在后台强制退出程序时就会走applicationWillTerminate 了.
    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
    
}

-(void)changeData
{
    [_timer invalidate];
    _timer = nil;
    
    MOUser *user = [MOUser sharedMOUser];
    NSString *str = user.userName;
    
    [MOUser clearUser];
    [[NSUserDefaults standardUserDefaults]setObject:str forKey:@"outName"];
    
    [self outLogin];
    
}

-(void)outVpn
{
    [_timer1 invalidate];
    _timer1 = nil;
    [[SDKWrapper getInstance] stop];
    [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"vpnLogin"];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    [_timer invalidate];
    _timer = nil;
    
    NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"enterBackTime"];
    if ([str integerValue]==1) {
        [[SDKWrapper getInstance] stop];
        MOOpenAppViewController *vc = [[MOOpenAppViewController alloc]init];
        [self.window setRootViewController:vc];
        [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"enterBackTime"];
    }

    NSString *stand = [[NSUserDefaults  standardUserDefaults] objectForKey:@"vpnLogin"];
    if ([stand integerValue]<=0) {
        [self vpnLogIn];
    }
    
}


- (void)applicationWillTerminate:(UIApplication *)application {
    NSLog(@"程序被杀死");

    MOUser *user = [MOUser sharedMOUser];
    NSString *str = user.userName;
    
    [MOUser clearUser];
    [[NSUserDefaults standardUserDefaults]setObject:str forKey:@"outName"];
    
    [self outVpn];
}


#pragma mark - UITabBarControllerDelegate

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    
    if (viewController == tabBarController.viewControllers[3]) {
//        if ([[ADUser sharedADUser].userId integerValue] == 0) {
//            ADLoginViewController *loginVC = [[ADLoginViewController alloc]init];
//            ADNavigationController *nav = [[ADNavigationController alloc] initWithRootViewController:loginVC];
//            [((UINavigationController *)tabBarController.selectedViewController) presentViewController:nav animated:YES completion:nil];
//            return NO;
//        }
    }
    
    return YES;
}



// Home+Power键截屏后通知响应的方法
- (void)userDidTakeScreenshotNotification:(NSNotification *)notification {
    // 下面这张图与硬件截的图并不是同一张，这里再次使用代码截屏是为了获取用户截屏图片。
//    UIImage *image = [self imageWithScreenshot];
    /*
     如果APP对保密要求比较高，这里可以将图片编码后上传到服务器，这样有需要时也可以提供一个追查方法。
     如果是自己的APP，再霸道一点的，这里监控到用户的截屏行为，应用直接强制退出登录并封号处理也是可以的。
     */
    
    MOHintView *hintView = [[MOHintView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) andContentStr:@"本App禁止截屏，再次截屏将做封号处理"];
    hintView.clickSureButtonBlock = ^{
        
    };
    [WINDOW addSubview:hintView];
    
}

// 代码截屏
- (UIImage *)imageWithScreenshot {
    CGSize imageSize = CGSizeZero;
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (UIInterfaceOrientationIsPortrait(orientation)) {
        imageSize = [UIScreen mainScreen].bounds.size;
    } else {
        imageSize = CGSizeMake([UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
    }
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
        CGContextSaveGState(context);
        CGContextTranslateCTM(context, window.center.x, window.center.y);
        CGContextConcatCTM(context, window.transform);
        CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y);
        if (orientation == UIInterfaceOrientationLandscapeLeft) {
            CGContextRotateCTM(context, M_PI_2);
            CGContextTranslateCTM(context, 0, -imageSize.width);
        } else if (orientation == UIInterfaceOrientationLandscapeRight) {
            CGContextRotateCTM(context, -M_PI_2);
            CGContextTranslateCTM(context, -imageSize.height, 0);
        } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
            CGContextRotateCTM(context, M_PI);
            CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);
        }
        if ([window respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
            [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES];
        } else {
            [window.layer renderInContext:context];
        }
        CGContextRestoreGState(context);
    }
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData *imageData = UIImagePNGRepresentation(image);
    UIImage *screenImage = [UIImage imageWithData:imageData];
    return screenImage;
}



#pragma mark Handle Open URL

- (BOOL)handleOpenURL:(NSURL*)url
{
    return [LibSecIDLite handleOpenURL:url];
}

#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_9_0
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    return [self handleOpenURL:url];
}
#else
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return [self handleOpenURL:url];
}

-(BOOL)application:(UIApplication *)application
           openURL:(NSURL *)url
 sourceApplication:(NSString *)sourceApplication
        annotation:(id)annotation {
    return [self handleOpenURL:url];
}
#endif

@end
